<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="70%"
    :close-on-click-modal="false"
    append-to-body
  >
    <el-scrollbar height="600px">
      <!-- 表单内容 -->
      <el-form
        ref="planForm"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <!-- 基本信息部分 -->
        <el-divider>基本信息</el-divider>
        <div class="form-row">
          <el-form-item label="*单位名称" prop="unitName">
            <el-input
              v-model="form.unitName"
              placeholder="请输入单位名称"
              :disabled="!isEdit"
            ></el-input>
          </el-form-item>
          <el-form-item label="*机构代码" prop="orgCode">
            <el-input
              v-model="form.orgCode"
              placeholder="请输入机构代码"
              :disabled="!isEdit"
            ></el-input>
          </el-form-item>
        </div>
        
        <div class="form-row">
          <el-form-item label="*法人代表" prop="legalPerson">
            <el-input
              v-model="form.legalPerson"
              placeholder="请输入法人代表"
              :disabled="!isEdit"
            ></el-input>
          </el-form-item>
          <el-form-item label="*法人电话" prop="legalPersonPhone">
            <el-input
              v-model="form.legalPersonPhone"
              placeholder="请输入法人电话"
              :disabled="!isEdit"
            ></el-input>
          </el-form-item>
        </div>
        
        <div class="form-row">
          <el-form-item label="联系人" prop="contactPerson">
            <el-input
              v-model="form.contactPerson"
              placeholder="请输入联系人"
              :disabled="!isEdit"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input
              v-model="form.contactPhone"
              placeholder="请输入联系电话"
              :disabled="!isEdit"
            ></el-input>
          </el-form-item>
        </div>
        
        <div class="form-row">
          <el-form-item label="传真号码" prop="faxNumber">
            <el-input
              v-model="form.faxNumber"
              placeholder="请输入传真号码"
              :disabled="!isEdit"
            ></el-input>
          </el-form-item>
          <el-form-item label="电子邮箱" prop="email">
            <el-input
              v-model="form.email"
              placeholder="请输入电子邮箱"
              :disabled="!isEdit"
            ></el-input>
          </el-form-item>
        </div>
        
        <div class="form-row">
          <el-form-item label="预案类型" prop="planType">
            <el-select
              v-model="form.planType"
              placeholder="请选择预案类型"
              :disabled="!isEdit"
            >
              <el-option label="突发环境事件应急预案" value="1"></el-option>
              <el-option label="其他类型预案" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="*行政区划" prop="adminArea">
            <el-select
              v-model="form.adminArea"
              placeholder="请选择行政区划"
              :disabled="!isEdit"
            >
              <el-option label="行政区划1" value="1"></el-option>
              <el-option label="行政区划2" value="2"></el-option>
            </el-select>
          </el-form-item>
        </div>
        
        <div class="form-row">
          <el-form-item label="备案时间" prop="recordTime">
            <el-date-picker
              v-model="form.recordTime"
              type="date"
              placeholder="请选择备案时间"
              value-format="yyyy-MM-dd"
              :disabled="!isEdit"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="备案编号" prop="recordNumber">
            <el-input
              v-model="form.recordNumber"
              placeholder="请输入备案编号"
              :disabled="!isEdit"
            ></el-input>
          </el-form-item>
        </div>
        
        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model="form.address"
            placeholder="请输入详细地址"
            :disabled="!isEdit"
          ></el-input>
        </el-form-item>
        
        <div class="form-row">
          <el-form-item label="*中心经度" prop="longitude">
            <el-input
              v-model="form.longitude"
              placeholder="请输入中心经度"
              type="number"
              step="0.000001"
              :disabled="!isEdit"
            ></el-input>
          </el-form-item>
          <el-form-item label="*中心纬度" prop="latitude">
            <el-input
              v-model="form.latitude"
              placeholder="请输入中心纬度"
              type="number"
              step="0.000001"
              :disabled="!isEdit"
            ></el-input>
          </el-form-item>
        </div>
        
        <div class="form-row">
          <el-form-item label="预案名称" prop="planName">
            <el-input
              v-model="form.planName"
              placeholder="请输入预案名称"
              :disabled="!isEdit"
            ></el-input>
          </el-form-item>
          <el-form-item label="版本号" prop="version">
            <el-input
              v-model="form.version"
              placeholder="请输入版本号"
              :disabled="!isEdit"
            ></el-input>
          </el-form-item>
        </div>
        
        <div class="form-row">
          <el-form-item label="*综合风险等级" prop="comprehensiveRiskLevel">
            <el-select
              v-model="form.comprehensiveRiskLevel"
              placeholder="请选择综合风险等级"
              :disabled="!isEdit"
            >
              <el-option label="一般风险" value="1"></el-option>
              <el-option label="较大风险" value="2"></el-option>
              <el-option label="重大风险" value="3"></el-option>
            </el-select>
          </el-form-item>
        </div>
        
        <div class="form-row">
          <el-form-item label="*大气风险等级" prop="airRiskLevel">
            <el-select
              v-model="form.airRiskLevel"
              placeholder="请选择大气风险等级"
              :disabled="!isEdit"
            >
              <el-option label="一般风险" value="1"></el-option>
              <el-option label="较大风险" value="2"></el-option>
              <el-option label="重大风险" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="Q" prop="airQ">
            <el-select
              v-model="form.airQ"
              placeholder="请选择Q"
              :disabled="!isEdit"
            >
              <el-option label="Q1" value="1"></el-option>
              <el-option label="Q2" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="M" prop="airM">
            <el-select
              v-model="form.airM"
              placeholder="请选择M"
              :disabled="!isEdit"
            >
              <el-option label="M1" value="1"></el-option>
              <el-option label="M2" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="E" prop="airE">
            <el-select
              v-model="form.airE"
              placeholder="请选择E"
              :disabled="!isEdit"
            >
              <el-option label="E1" value="1"></el-option>
              <el-option label="E2" value="2"></el-option>
            </el-select>
          </el-form-item>
        </div>
        
        <div class="form-row">
          <el-form-item label="*水风险等级" prop="waterRiskLevel">
            <el-select
              v-model="form.waterRiskLevel"
              placeholder="请选择水风险等级"
              :disabled="!isEdit"
            >
              <el-option label="一般风险" value="1"></el-option>
              <el-option label="较大风险" value="2"></el-option>
              <el-option label="重大风险" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="Q" prop="waterQ">
            <el-select
              v-model="form.waterQ"
              placeholder="请选择Q"
              :disabled="!isEdit"
            >
              <el-option label="Q1" value="1"></el-option>
              <el-option label="Q2" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="M" prop="waterM">
            <el-select
              v-model="form.waterM"
              placeholder="请选择M"
              :disabled="!isEdit"
            >
              <el-option label="M1" value="1"></el-option>
              <el-option label="M2" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="E" prop="waterE">
            <el-select
              v-model="form.waterE"
              placeholder="请选择E"
              :disabled="!isEdit"
            >
              <el-option label="E1" value="1"></el-option>
              <el-option label="E2" value="2"></el-option>
            </el-select>
          </el-form-item>
        </div>
        
        <div class="form-row">
          <el-form-item label="风险级别" prop="riskLevel">
            <el-input
              v-model="form.riskLevel"
              placeholder="请输入风险级别"
              :disabled="!isEdit"
            ></el-input>
          </el-form-item>
          <el-form-item label="*是否自贸区" prop="isFreeTradeZone">
            <el-select
              v-model="form.isFreeTradeZone"
              placeholder="请选择是否自贸区"
              :disabled="!isEdit"
            >
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="0"></el-option>
            </el-select>
          </el-form-item>
        </div>
        
        <el-form-item>
          <div class="declaration">
            <p>本单位于{{ form.declarationDate || '选择日期时间' }}签署发布了突发环境事件应急预案，预案条件具备，预案文件齐全，预案完备。本单位承诺，本单位在办理备案中所提供的相关文件及其信息均经本单位认真确认，无虚假，且未隐瞒事实。</p>
          </div>
        </el-form-item>
        
        <div class="form-row">
          <el-form-item label="预案签署人" prop="signer">
            <el-input
              v-model="form.signer"
              placeholder="请输入预案签署人"
              :disabled="!isEdit"
            ></el-input>
          </el-form-item>
          <el-form-item label="审核时间" prop="auditTime">
            <el-date-picker
              v-model="form.auditTime"
              type="date"
              placeholder="请选择审核时间"
              value-format="yyyy-MM-dd"
              :disabled="!isEdit"
            ></el-date-picker>
          </el-form-item>
        </div>
        
        <!-- 文件上传部分 -->
        <el-divider>文件上传</el-divider>
        <div class="upload-section">
          <!-- 两列网格布局 -->
          <div class="upload-grid">
            <!-- 第一列 -->
            <div class="upload-column">
              <el-form-item label="1.预案签署页" prop="signatureFile">
                <el-upload
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :file-list="signatureFileList"
                  :on-success="handleSignatureFileSuccess"
                  :on-remove="handleSignatureFileRemove"
                  :before-upload="beforeSignatureFileUpload"
                  :disabled="!isEdit"
                  accept=".png,.jpg,.jpeg"
                >
                  <el-button size="small" type="primary">选取文件</el-button>
                  <div slot="tip" class="el-upload__tip">请上传大小不超过10MB格式为png/jpg/jpeg的文件</div>
                </el-upload>
              </el-form-item>
              
              <el-form-item label="3.环境应急预案及编制说明" prop="planDocFile">
                <el-upload
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :file-list="planDocFileList"
                  :on-success="handlePlanDocFileSuccess"
                  :on-remove="handlePlanDocFileRemove"
                  :before-upload="beforeDocumentFileUpload"
                  :disabled="!isEdit"
                  accept=".doc,.docx,.pdf"
                >
                  <el-button size="small" type="primary">选取文件</el-button>
                  <div slot="tip" class="el-upload__tip">请上传大小不超过50MB格式为doc/docx/pdf的文件</div>
                </el-upload>
              </el-form-item>
              
              <el-form-item label="5.环境应急资源调查报告" prop="resourceSurveyFile">
                <el-upload
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :file-list="resourceSurveyFileList"
                  :on-success="handleResourceSurveyFileSuccess"
                  :on-remove="handleResourceSurveyFileRemove"
                  :before-upload="beforeDocumentFileUpload"
                  :disabled="!isEdit"
                  accept=".doc,.docx,.pdf"
                >
                  <el-button size="small" type="primary">选取文件</el-button>
                  <div slot="tip" class="el-upload__tip">请上传大小不超过50MB格式为doc/docx/pdf的文件</div>
                </el-upload>
              </el-form-item>
            </div>
            
            <!-- 第二列 -->
            <div class="upload-column">
              <el-form-item label="2.突发环境事件应急预案备案表" prop="recordFormFile">
                <el-upload
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :file-list="recordFormFileList"
                  :on-success="handleRecordFormFileSuccess"
                  :on-remove="handleRecordFormFileRemove"
                  :before-upload="beforeDocumentFileUpload"
                  :disabled="!isEdit"
                  accept=".doc,.docx,.pdf"
                >
                  <el-button size="small" type="primary">选取文件</el-button>
                  <div slot="tip" class="el-upload__tip">请上传大小不超过50MB格式为doc/docx/pdf的文件</div>
                </el-upload>
              </el-form-item>
              
              <el-form-item label="4.环境风险评估报告" prop="riskAssessmentFile">
                <el-upload
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :file-list="riskAssessmentFileList"
                  :on-success="handleRiskAssessmentFileSuccess"
                  :on-remove="handleRiskAssessmentFileRemove"
                  :before-upload="beforeDocumentFileUpload"
                  :disabled="!isEdit"
                  accept=".doc,.docx,.pdf"
                >
                  <el-button size="small" type="primary">选取文件</el-button>
                  <div slot="tip" class="el-upload__tip">请上传大小不超过50MB格式为doc/docx/pdf的文件</div>
                </el-upload>
              </el-form-item>
              
              <el-form-item label="6.环境应急预案评审意见" prop="reviewOpinionFile">
                <el-upload
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :file-list="reviewOpinionFileList"
                  :on-success="handleReviewOpinionFileSuccess"
                  :on-remove="handleReviewOpinionFileRemove"
                  :before-upload="beforeDocumentFileUpload"
                  :disabled="!isEdit"
                  accept=".doc,.docx,.pdf"
                >
                  <el-button size="small" type="primary">选取文件</el-button>
                  <div slot="tip" class="el-upload__tip">请上传大小不超过50MB格式为doc/docx/pdf的文件</div>
                </el-upload>
              </el-form-item>
            </div>
          </div>
          
          <div class="form-row">
            <el-form-item label="审核环保局" prop="auditBureau">
              <el-select
                v-model="form.auditBureau"
                placeholder="请选择审核分局"
                :disabled="!isEdit"
              >
                <el-option label="环保局1" value="1"></el-option>
                <el-option label="环保局2" value="2"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
      </el-form>
    </el-scrollbar>
    
    <!-- 底部按钮 -->
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" v-if="isEdit" @click="submitForm">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'PlanDialog',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    dialogType: {
      type: String,
      default: 'view' // view 或 edit
    },
    planData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      form: {
        unitName: '',
        orgCode: '',
        legalPerson: '',
        legalPersonPhone: '',
        contactPerson: '',
        contactPhone: '',
        faxNumber: '',
        email: '',
        planType: '',
        adminArea: '',
        recordTime: '',
        recordNumber: '',
        address: '',
        longitude: '',
        latitude: '',
        planName: '',
        version: '',
        comprehensiveRiskLevel: '',
        airRiskLevel: '',
        airQ: '',
        airM: '',
        airE: '',
        waterRiskLevel: '',
        waterQ: '',
        waterM: '',
        waterE: '',
        riskLevel: '',
        isFreeTradeZone: '',
        declarationDate: '',
        signer: '',
        auditTime: '',
        auditBureau: '',
        // 文件相关字段
        signatureFile: '',
        recordFormFile: '',
        planDocFile: '',
        riskAssessmentFile: '',
        resourceSurveyFile: '',
        reviewOpinionFile: ''
      },
      rules: {
        unitName: [
          { required: true, message: '请输入单位名称', trigger: 'blur' }
        ],
        orgCode: [
          { required: true, message: '请输入机构代码', trigger: 'blur' }
        ],
        legalPerson: [
          { required: true, message: '请输入法人代表', trigger: 'blur' }
        ],
        legalPersonPhone: [
          { required: true, message: '请输入法人电话', trigger: 'blur' }
        ],
        adminArea: [
          { required: true, message: '请选择行政区划', trigger: 'change' }
        ],
        longitude: [
          { required: true, message: '请输入中心经度', trigger: 'blur' },
          { type: 'number', message: '经度必须为数字', trigger: 'blur' }
        ],
        latitude: [
          { required: true, message: '请输入中心纬度', trigger: 'blur' },
          { type: 'number', message: '纬度必须为数字', trigger: 'blur' }
        ],
        comprehensiveRiskLevel: [
          { required: true, message: '请选择综合风险等级', trigger: 'change' }
        ],
        airRiskLevel: [
          { required: true, message: '请选择大气风险等级', trigger: 'change' }
        ],
        waterRiskLevel: [
          { required: true, message: '请选择水风险等级', trigger: 'change' }
        ],
        isFreeTradeZone: [
          { required: true, message: '请选择是否自贸区', trigger: 'change' }
        ]
      },
      // 文件上传相关
      uploadUrl: '/common/upload',
      uploadHeaders: {
        'Authorization': 'Bearer ' + this.$cookie.get('token')
      },
      // 文件列表
      signatureFileList: [],
      recordFormFileList: [],
      planDocFileList: [],
      riskAssessmentFileList: [],
      resourceSurveyFileList: [],
      reviewOpinionFileList: []
    }
  },
  computed: {
    // 弹窗标题
    dialogTitle() {
      return this.dialogType === 'view' ? '预案详情' : '修改预案';
    },
    // 是否可编辑
    isEdit() {
      return this.dialogType === 'edit';
    }
  },
  watch: {
    // 监听弹窗显示状态
    dialogVisible(val) {
      if (val) {
        this.initData();
      } else {
        this.resetForm();
      }
    },
    // 监听预案数据变化
    planData: {
      handler(val) {
        if (this.dialogVisible) {
          this.initData();
        }
      },
      deep: true
    }
  },
  methods: {
    // 初始化数据
    initData() {
      // 清空表单和文件列表
      this.resetForm();
      
      // 如果有数据，填充表单
      if (this.planData && Object.keys(this.planData).length > 0) {
        // 复制数据到表单
        this.form = { ...this.planData };
        
        // 初始化文件列表
        if (this.planData.signatureFile) {
          this.signatureFileList = [{
            name: this.getFileName(this.planData.signatureFile),
            url: this.planData.signatureFile
          }];
        }
        if (this.planData.recordFormFile) {
          this.recordFormFileList = [{
            name: this.getFileName(this.planData.recordFormFile),
            url: this.planData.recordFormFile
          }];
        }
        if (this.planData.planDocFile) {
          this.planDocFileList = [{
            name: this.getFileName(this.planData.planDocFile),
            url: this.planData.planDocFile
          }];
        }
        if (this.planData.riskAssessmentFile) {
          this.riskAssessmentFileList = [{
            name: this.getFileName(this.planData.riskAssessmentFile),
            url: this.planData.riskAssessmentFile
          }];
        }
        if (this.planData.resourceSurveyFile) {
          this.resourceSurveyFileList = [{
            name: this.getFileName(this.planData.resourceSurveyFile),
            url: this.planData.resourceSurveyFile
          }];
        }
        if (this.planData.reviewOpinionFile) {
          this.reviewOpinionFileList = [{
            name: this.getFileName(this.planData.reviewOpinionFile),
            url: this.planData.reviewOpinionFile
          }];
        }
      }
    },
    
    // 重置表单
    resetForm() {
      this.$nextTick(() => {
        if (this.$refs.planForm) {
          this.$refs.planForm.resetFields();
        }
      });
      
      // 重置文件列表
      this.signatureFileList = [];
      this.recordFormFileList = [];
      this.planDocFileList = [];
      this.riskAssessmentFileList = [];
      this.resourceSurveyFileList = [];
      this.reviewOpinionFileList = [];
      
      // 重置表单数据
      this.form = {
        unitName: '',
        orgCode: '',
        legalPerson: '',
        legalPersonPhone: '',
        contactPerson: '',
        contactPhone: '',
        faxNumber: '',
        email: '',
        planType: '',
        adminArea: '',
        recordTime: '',
        recordNumber: '',
        address: '',
        longitude: '',
        latitude: '',
        planName: '',
        version: '',
        comprehensiveRiskLevel: '',
        airRiskLevel: '',
        airQ: '',
        airM: '',
        airE: '',
        waterRiskLevel: '',
        waterQ: '',
        waterM: '',
        waterE: '',
        riskLevel: '',
        isFreeTradeZone: '',
        declarationDate: '',
        signer: '',
        auditTime: '',
        auditBureau: '',
        signatureFile: '',
        recordFormFile: '',
        planDocFile: '',
        riskAssessmentFile: '',
        resourceSurveyFile: '',
        reviewOpinionFile: ''
      };
    },
    
    // 提交表单
    submitForm() {
      this.$refs.planForm.validate((valid) => {
        if (valid) {
          // 提交数据到父组件
          this.$emit('submit', this.form);
          // 关闭弹窗
          this.$emit('update:dialogVisible', false);
        } else {
          return false;
        }
      });
    },
    
    // 获取文件名
    getFileName(fileUrl) {
      if (!fileUrl) return '';
      const parts = fileUrl.split('/');
      return parts[parts.length - 1];
    },
    
    // 图片文件上传前检查
    beforeSignatureFileUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10;
      const isImage = ['image/png', 'image/jpeg', 'image/jpg'].includes(file.type);
      
      if (!isImage) {
        this.$message.error('只能上传PNG、JPG、JPEG格式的图片！');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过10MB！');
        return false;
      }
      return true;
    },
    
    // 文档文件上传前检查
    beforeDocumentFileUpload(file) {
      const isLt50M = file.size / 1024 / 1024 < 50;
      const isDocument = ['application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/pdf'].includes(file.type);
      
      if (!isDocument) {
        this.$message.error('只能上传DOC、DOCX、PDF格式的文档！');
        return false;
      }
      if (!isLt50M) {
        this.$message.error('上传文件大小不能超过50MB！');
        return false;
      }
      return true;
    },
    
    // 文件上传成功处理函数
    handleSignatureFileSuccess(response, file, fileList) {
      this.form.signatureFile = response.url;
    },
    handleRecordFormFileSuccess(response, file, fileList) {
      this.form.recordFormFile = response.url;
    },
    handlePlanDocFileSuccess(response, file, fileList) {
      this.form.planDocFile = response.url;
    },
    handleRiskAssessmentFileSuccess(response, file, fileList) {
      this.form.riskAssessmentFile = response.url;
    },
    handleResourceSurveyFileSuccess(response, file, fileList) {
      this.form.resourceSurveyFile = response.url;
    },
    handleReviewOpinionFileSuccess(response, file, fileList) {
      this.form.reviewOpinionFile = response.url;
    },
    
    // 文件删除处理函数
    handleSignatureFileRemove(file, fileList) {
      this.form.signatureFile = '';
    },
    handleRecordFormFileRemove(file, fileList) {
      this.form.recordFormFile = '';
    },
    handlePlanDocFileRemove(file, fileList) {
      this.form.planDocFile = '';
    },
    handleRiskAssessmentFileRemove(file, fileList) {
      this.form.riskAssessmentFile = '';
    },
    handleResourceSurveyFileRemove(file, fileList) {
      this.form.resourceSurveyFile = '';
    },
    handleReviewOpinionFileRemove(file, fileList) {
      this.form.reviewOpinionFile = '';
    },
    
    // 处理取消
    handleCancel() {
      this.$emit('update:dialogVisible', false);
    }
  }
}
</script>

<style scoped>
.form-row {
  display: flex;
  margin-bottom: 20px;
}

.form-row .el-form-item {
  margin-right: 20px;
  margin-bottom: 0;
  flex: 1;
}

.form-row .el-form-item:last-child {
  margin-right: 0;
}

.declaration {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.5;
}

/* 两列网格布局 */
.upload-grid {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10px;
}

.upload-column {
  flex: 1;
  min-width: 45%;
  padding: 0 10px;
}

.upload-section .el-form-item {
  margin-bottom: 15px;
}

.dialog-footer {
  text-align: center;
}
</style>